import Setting from "@/config/setting";
import Log from "./Log";
import Cookies from "./cookies";

const URL = Symbol("URL");
const _option = Symbol("_option");

/**
 * 封装后的request
 * baseUrl: String;
 * path: String
 * interface option{
 *  tokenValidity : Number;
 *  timeout:Number;
 *  header : Object
 * }
 */
class _Request {
  [URL] =
    Setting.ENV === "development" ? Setting.devBaseUrl : Setting.proBaseUrl;

  [_option] = {
    header: {
      // "Content-Type": "application/x-www-form-urlencoded",
      "Content-Type": "application/json"
    },
    timeout: Setting.timeout,
  };

  static httpCodeStatus = {
    400: "请求错误",
    401: "未授权，请登录",
    403: "拒绝访问",
    404: `请求地址出错: ${this.currentURL}`,
    408: "请求超时",
    500: "服务器内部错误",
    501: "服务未实现",
    502: "网关错误",
    503: "服务不可用",
    504: "网关超时",
    505: "HTTP版本不受支持",
  };

  constructor(option) {
    this.option = Object.assign({}, this[_option], option);
    this.currentURL = "";
    this.noSessionKey = false;
  }

  heanleURL(path) {
    const regex = new RegExp(/^http/);
    this.currentURL = regex.test(path) ? path : this[URL] + path;
    return this.currentURL;
  }

  /**
   * @description 请求方法
   * method: String
   * path: String;
   * data:  Object | String | ArrayBuffer;
   * noSessionKey: Boolean;
   */
  request(method = "GET", url, data, noSessionKey = false) {
    const { header, timeout } = this.option;
    console.log(noSessionKey);
    this.noSessionKey = noSessionKey;
    
    return new Promise((resolve, reject) => {
      uni.request({
        method,
        url,
        timeout,
        header,
        data,
        success: (res) => {
          resolve(res)
        },
        fail: (res) => {
          if (Setting.ENV === "development") {
            uni.showToast({
              title: _Request.httpCodeStatus[res.code],
              icon: "none",
            });
          }
          reject(res);
        },
      });
    });
  }
}

const Service = new _Request();
// 请求拦截
uni.addInterceptor("request", {
  invoke(args) {
    console.log(args);
    // request 触发前拼接 url
    args.url = Service.heanleURL(args.url)
    // noSessionKey true时，请求头不带上session_key
    if (!Service.noSessionKey){
    if(typeof Cookies.get("user")!=='undefined' )args.header.accessToken = Cookies.get("user").token
    }

    // Cookies.get("AppID")
    args.header = {
      ...args.header,
      appId:'2021002185664359',
    };
    return args;
  },
  success(res) {
    console.log("interceptor-success", res);
    // 401 跳转登录页面
    if (res.data.code === 401) {
      uni.navigateTo({
        url: '/pages/account/login'
    });
    }
  },
  fail(err) {
    console.log("interceptor-fail", err);
  },
  complete(res) {
    console.log("interceptor-complete", res);
  },
  // 返回值
  // returnValue(e) {
    // 处理返回结果
    // console.log('返回值',e);
    // return e;
  // },
});

export default Service;
